﻿CREATE PROCEDURE [dbo].[user_Share_HashCode]
	@chapterId bigint,
	@userId uniqueidentifier
AS
BEGIN
	DECLARE @shareHashCode NVARCHAR(128)

	SELECT @shareHashCode = [HashCode] FROM [dbo].[user_Share] WHERE [TextId] = @chapterId AND [UserId] = @userId

	IF @shareHashCode IS NULL
	BEGIN
		BEGIN TRAN

			SET @shareHashCode = CAST([dbo].[RandString](128) AS NVARCHAR(128))
			WHILE EXISTS (SELECT * FROM [dbo].[user_Share] WHERE [HashCode] = @shareHashCode)
			BEGIN
				SET @shareHashCode = CAST([dbo].[RandString](128) AS NVARCHAR(128))
			END

			INSERT INTO [dbo].[user_Share]
							([HashCode], [UserId], [TextId])
			VALUES	(@shareHashCode, @userId, @chapterId)


		COMMIT TRAN
	END

	SELECT @shareHashCode AS 'ShareHashCode'

END